<template>
  <div>
    <div style="display: flex; justify-content: flex-end;margin: 10px">
      <a-button type="primary" @click="editClass(null)">新增账号</a-button>
    </div>

    <a-table
      :columns="columns"
      bordered
      :dataSource="dataTable"
      @change="tableChange"
      :pagination="{
        pageSize: form.size,
        total: totalPage,
        current: form.page
      }"
    >
      <template slot="headUrl" slot-scope="text, record, index">
        <img
          :src="text"
          v-if="text"
          alt="头像"
          style="width:60px;"
          @click="previewImage({ url: text })"
        />
      </template>
      <template slot="operation" slot-scope="text, row, index">
        <a-button size="small" type="primary" @click="editClass(row)"
          >编辑</a-button
        >
        <a-popconfirm
          title="你确定更要删除吗?"
          @confirm="delPlan(row)"
          @cancel="cancel"
          okText="确定"
          cancelText="取消"
        >
          <a-button size="small" type="danger">删除</a-button>
        </a-popconfirm>
      </template>
    </a-table>

    <!-- 弹框 -->
    <a-modal
      :title="this.modelTittle"
      :visible="visibleDetails"
      @cancel="offModel"
      cancelText="关闭"
      okText="确定"
      @ok="handleSubmit"
    >
      <a-form :form="formData">
        <!-- <a-form-item
          label="头像"
          :label-col="{ span: 5 }"
          :wrapper-col="{ span: 12 }"
        >
          <a-upload
            v-decorator="['file', { initialValue: file }]"
            list-type="picture-card"
            class="avatar-uploader"
            :show-upload-list="false"
            :before-upload="beforeUpload"
            :customRequest="selfUpload"
            @change="handleChange"
          >
            <img style="width: 180px" v-if="imageUrl" :src="imageUrl" />
            <div v-else>
              <a-icon type="plus" />
              <div class="ant-upload-text">上传图片</div>
            </div>
          </a-upload>
        </a-form-item> -->
        <a-form-item
          label="登录账号"
          :label-col="{ span: 5 }"
          :wrapper-col="{ span: 12 }"
        >
          <a-input
            v-decorator="[
              'account',
              {
                initialValue: account,
                rules: [{ required: true, message: '请输入登录账号' }]
              }
            ]"
          ></a-input>
        </a-form-item>
        <a-form-item
          label="密码"
          :label-col="{ span: 5 }"
          :wrapper-col="{ span: 12 }"
        >
          <a-input
            type="password"
            v-decorator="[
              'password',
              {
                initialValue: password,
                rules: [{ required: true, message: '请输入密码' }]
              }
            ]"
          ></a-input>
        </a-form-item>
        <a-form-item
          label="角色权限"
          :label-col="{ span: 5 }"
          :wrapper-col="{ span: 12 }"
        >
          <a-select
            placeholder="请选择角色权限"
            v-decorator="['roleId', { initialValue: roleName }]"
          >
            <a-select-option
              v-for="r in roleId"
              :key="r.value"
              :value="r.value"
              >{{ r.text }}</a-select-option
            >
          </a-select>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>
<script>
import api from "@/api/api.js";
import UploadImg from "../../components/uploadImg.vue";
import { quillEditor } from "vue-quill-editor";
import { quillRedefine } from "vue-quill-editor-upload";
import "quill/dist/quill.core.css";
import "quill/dist/quill.snow.css";
import "quill/dist/quill.bubble.css";

function getBase64(img, callback) {
  const reader = new FileReader();
  reader.addEventListener("load", () => callback(reader.result));
  reader.readAsDataURL(img);
}
export default {
  components: {
    UploadImg
  },
  data() {
    return {
      visibleDetails: false,
      modelTittle: "",
      dataTable: [],
      columns: [
        ,
        //  {
        //     title: '头像',
        //     dataIndex: 'headUrl',
        //     align:'center',
        //     copedSlots: { customRender: 'headUrl' },
        // }
        {
          title: "登录账号",
          dataIndex: "account",
          align: "center"
        },
        {
          title: "密码",
          key: "password",
          dataIndex: "password",
          align: "center"
        },
        {
          title: "角色权限",
          dataIndex: "roleName",
          align: "center"
        },
        {
          title: "创建时间",
          dataIndex: "createTime",
          align: "center"
        },
        {
          title: "操作",
          key: "operation",
          dataIndex: "operation",
          align: "center",
          scopedSlots: { customRender: "operation" }
        }
      ],
      rowSelection: {
        hideDefaultSelections: true
      },
      form: {
        size: 10, //每页条数
        page: 1 // 起始页
      },
      totalPage: 0,
      showHOST: api.showHOST,
      radioType: 2,
      formData: this.$form.createForm(this),
      account: "",
      password: "",
      roleId: [],
      file: [],
      roleName: "",
      accountId: "",
      imageUrl: ""
    };
  },
  methods: {
    tableChange(pagination, filters, sorter) {
      this.form.page = pagination.current;
      this.getPlan();
    },
    change(data) {
      this.file = data;
    },
    cancel(e) {
      this.$message.error("取消!");
    },
    offModel() {
      this.visibleDetails = false;
      this.roleId = [];
      (this.imageUrl = ""), this.formData.resetFields();
    },
    getPlan() {
      api.getUserList(this.form).then(res => {
        console.log(res);
        if (res.code == 200) {
          this.totalPage = res.result.totalCount;
          this.dataTable = res.result.content;
        }
      });
    },
    editClass(row) {
      this.roleName = undefined;
      this.imageUrl = "";
      api.getRoleList(this.form).then(res => {
        if (res.code == 200) {
          res.result.forEach(r => {
            this.roleId.push({
              value: r.roleId,
              text: r.roleName
            });
          });
        }
      });
      if (row === null) {
        this.account = "";
        this.password = "";
        this.visibleDetails = true;
        this.modelTittle = "新增账号";
      } else {
        this.visibleDetails = true;
        this.modelTittle = "修改信息";
        this.account = row.account;
        this.password = row.password;
        this.accountId = row.accountId;
        this.imageUrl = row.headUrl;
        if (row.roleId != null) {
          this.roleName = row.roleId;
        }
      }
    },
    delPlan(row) {
      api.delAccount({ userId: row.accountId }).then(res => {
        if (res.code == 200) {
          this.getPlan();
        } else {
          this.$message.error(res.result);
        }
      });
    },
    handleSubmit(e) {
      this.formData.validateFields((err, values) => {
        if (!err) {
          if (this.modelTittle == "修改信息") {
            //  values.roleId = this.roleId;
            //  values.status = this.rowData.status;
            values.accountId = this.accountId;
          }
          const f = new FormData();
          if (values.file != undefined) {
            f.append("file", values.file.file);
          }
          values.file = f;
          api.saveUser(values).then(res => {
            if (res.code == 200) {
              this.visibleDetails = false;
              this.roleId = [];
              this.file = [];
              this.formData.resetFields();
              this.getPlan();
            } else {
              this.$message.error(res.description);
            }
          });
        }
      });
    },
    previewImage(file) {
      console.log(file);
      window.open(file.url);
    },
    beforeUpload(file) {
      const isJpgOrPng =
        file.type === "image/jpeg" || file.type === "image/png";
      if (!isJpgOrPng) {
        this.$message.error("请上传jpeg或png格式的图片!");
      }
      const isLt2M = file.size / 1024 / 1024 < 5;
      if (!isLt2M) {
        this.$message.error("图片大小不能小于5兆!");
      }
      return isJpgOrPng && isLt2M;
    },
    selfUpload({ action, file, onSuccess, onError, onProgress }) {},
    handleChange(info) {
      // Get this url from response in real world.
      getBase64(info.file.originFileObj, imageUrl => {
        this.imageUrl = imageUrl;
        this.loading = false;
      });
    }
  },
  created() {
    this.getPlan();
  }
};
</script>

<style lang="scss" scoped="" type="text/css">
.editable-row-operations a {
  margin-right: 8px;
}
.top-btn {
  padding: 10px;
}
.code-img {
  display: block;
  width: 150px;
}
</style>
